package com.chen.aspectj;

import com.chen.annotation.Counter;
import com.chen.annotation.RateLimiter;
import com.chen.enums.CounterType;
import com.chen.enums.LimitType;
import com.chen.exception.ServiceException;
import com.chen.utils.DateUtils;
import com.chen.utils.ServletUtils;
import com.chen.utils.StringUtils;
import com.chen.utils.ip.IpUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 计数处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class CounterAspect {
    private static final Logger log = LoggerFactory.getLogger(CounterAspect.class);

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Before("@annotation(counter)")
    public void doBefore(JoinPoint point, Counter counter) throws Throwable {
        String combineKey = getCombineKey(counter, point);
        Long increment = redisTemplate.opsForValue().increment(combineKey);
        log.info("缓存key:{}，接口访问次数为{}", combineKey, increment);
    }

    public String getCombineKey(Counter counter, JoinPoint point) {
        StringBuilder stringBuffer = new StringBuilder(counter.prefix());
        stringBuffer.append(DateUtils.parseDateToStr("yyyyMMdd", new Date())).append("-");
        if (counter.type() == CounterType.IP) {
            stringBuffer.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append("-");
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        return stringBuffer.toString();
    }
}
